package com.axin.blog.api.config;

import cn.hutool.core.util.ObjectUtil;
import com.axin.common.core.constant.SecurityConstants;
import com.axin.common.core.utils.IpUtils;
import com.axin.common.core.utils.ServletUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * feign 请求拦截器
 *
 * @author ruoyi
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest();
        if (ObjectUtil.isNotNull(httpServletRequest)) {
            Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);

            String authentication = headers.get(SecurityConstants.TOKEN_AUTHENTICATION);
            if (StringUtils.isNotEmpty(authentication)) {
                requestTemplate.header(SecurityConstants.TOKEN_AUTHENTICATION, authentication);
            }

            // 配置客户端IP
            requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));
        }
    }
}